


var data1 = [{'id':'1','customerstype':'text1','customerstname':'text2','cucustomerscode':'text3','referred':'text4','countries':'text5','customerlevel':'text6','customersource':'text7','businesstypes':'text8','url':'text9','subordinatesalesman':'text10'}];

var layer = layui.layer //弹层
    ,table = layui.table //表格
    form = layui.form,$ = layui.jquery, element = layui.element
     ,flag=getQueryVariable("flag")///flag=kzt
        ,type=getQueryVariable("type")//控制台传过来参数
        ,type2=getQueryVariable("type")//控制台传过来参数
      ,distributionid="",lxrname="",lxremail="",processid=""
    ;
var sharecustomer = [];//共享客户id列表
//当前登录人所管理的员工
var manageRuls=JSON.parse(window.sessionStorage.getItem("manageRuls"));//=getManageRule("CustomerSalesman","customer","operator");
var userTree=JSON.parse(window.sessionStorage.getItem("userTree"));
var userAllTree=JSON.parse(window.sessionStorage.getItem("userAllTree"));

//从字典中获取信息
var djs=JSON.parse(window.sessionStorage.getItem("djs"));//=getdictionaryF(6,26);//客户等级
var fls=JSON.parse(window.sessionStorage.getItem("fls"));//=getdictionary(6,27);//客户类型
var countrys=JSON.parse(window.sessionStorage.getItem("countrys"));//=getdictionaryF(6,29);//国家/地区
var sourceOfCustomerss=JSON.parse(window.sessionStorage.getItem("sourceOfCustomerss"));//=getdictionaryF(1,3);//客户来源
var attributesOfCustomers=JSON.parse(window.sessionStorage.getItem("attributesOfCustomers"));//=getdictionaryF(1,87);//客户属性
var businessTypes=JSON.parse(window.sessionStorage.getItem("businessTypes"));//=getdictionaryF(6,33);//业务类型
var spstatuss=JSON.parse(window.sessionStorage.getItem("spstatuss"));//=getdictionaryF(6,34);//审批状态
var salemans=manageRuls;

let salesmanCodes="";//所属 业务员下拉框选择值
let sourceOfCustomerList=[];//客户来源下拉框选择值
let attributesOfCustomerList=[];//客户属性下拉框选择值
let isMakerList=[];//是否成单下拉框选择值
let share22="";
let shareopenwind;
//判断是否是客户还是供应商
/*if(flag=="gys"){
    $("#khpool").css("display","none");
    $("#khpooldiv").css("display","none");
    $("button#addpubpool.layui-btn.layui-btn-sm").css("display","none")
}*/
//客户类型查询条件赋值
//setType();
if(type==""){
    for(var i=0;i<fls.length;i++){
        type=type+","+fls[i].code;
    }
}

//添加打印按钮
// let printBut=document.getElementsByClassName("layui-table-tool-temp");
// printBut[0].innerHTML='<a class="layui-btn layui-btn-sm layui-btn-danger" id="print" style="margin-left: 10px" lay-event="print">打印</a>';

let userCodes='RKB005,RKB006,RKB003,admin'
if (userCodes.indexOf(user.code)!=-1){
    document.getElementById("commonsettings").style.display = "block";
}

//判断当前登录用户是否为 营销部门的总监 角色 true:是 false 否
let isMarketingDirector=false;
is_marketing_director();

layer.ready(function () {
    //获取所有用户信息
    $.ajax({
        url:"otherOutStock/getAllUserInfo",
        success:function(data){
            if(data.status == 200){
                for(let i in data.data){
                    $("#salesmanCode").append("<option value=\"" + data.data[i].code + "\">" + data.data[i].name + "</option>");
                }
                form.render('select');
            }
        }
    });

    let customerType=JSON.parse(window.sessionStorage.getItem("fls"));//客户等级

    for(let i in customerType){
        if (customerType[i].name.indexOf("合作")!=-1){
            $('#customerType').append(new Option(customerType[i].name, customerType[i].code));
        }
    }

});

function init(){
    //从字典中获取信息
     djs=getdictionarF(6,26);//客户等级
     fls=getdictionarF(6,27);//客户类型
     countrys=getdictionarF(6,29);//国家/地区
     sourceOfCustomerss=getdictionarF(1,3);//客户来源
     businessTypes=getdictionarF(6,33);//业务类型
     spstatuss=getdictionarF(6,34);//审批状态
     salemans=manageRuls;
    initable22();
    //initable33();
    getxmselect2("#cucustomerstype2","cucustomerstype1", getxmlselectfls(fls));
    getxmselect2("#cucustomerstype22","cucustomerstype22", getxmlselectfls(fls));
    cunt=1;
}
//---客户查询
table.render({
    elem: '#customerselect'
    //,data:data1
    , type: 'get'
    , url: 'customer/selectByPage'
    ,where:{
        "type":type,
        "type2":type2,
        "name":"",
        "saleman":"",//user.customerRole,
        "flag":flag
    }
   // ,defaultToolbar:["filter","exports","print"]
    , toolbar: true
    , cols: [[
        {checkbox: true, fixed: true}
        , {field: 'type', title: '客户类型',width: 220}
        , {field: 'name', title: '客户名称', event: "customerstname",width: 220}
        , {field: 'code', title: '客户代码', event: "cucustomerscode",width: 100}
        , {field: 'abbreviation', title: '简称', event: "referred",width: 100}
        , {field: 'country', title: '国家',width: 100 }
        , {field: 'level', title: '客户等级' ,width: 100}
        , {field: 'sourceOfCustomers', title: '客户来源' ,width: 200}
        , {field: 'attributesOfCustomers', title: '客户属性' ,width: 200}
        , {field: 'businessType', title: '业务类型',width: 100 }
        , {field: 'shortCode', title: '客户三位简码',width: 200 }
        , {field: 'salesman', title: '所属业务员',width: 150}
        , {field: 'accountPeriod', title: '帐期',width: 100}
        , {field: 'isMaker', title: '是否成单',width: 100}
        , {field: 'createtime', title: '创建时间',width: 130}
        , {field: 'updatetime', title: '更新时间',width: 130}
        , {fixed: 'right', width: 300, align: 'center', toolbar: '#customerup', title: '操作'}
    ]]
    , id: 'customertableid'
    , height: $(document).height() - $('#customerselect').offset().top - 50
    , page: true
    , limit: 50
    , limits: [50, 100, 150,200]
    , done: function (res, curr, count) {


        //客户类型
         getselectText(fls,"type");
        //国家
        getselectText(countrys,"country");
        //客户等级
        getselectText(djs,"level");
        //客户来源
        getselectText(sourceOfCustomerss,"sourceOfCustomers");
        //业务类型
        getselectText(businessTypes,"businessType");
        //审批状态
        getselectText(spstatuss,"spstatus");
        //查询条件中类型
        //initable22();
       // setselecttype(fls,"cucustomerstype1");
       /* var options="";
        for(var i=0;i<fls.length;i++){
            options+="<option value='"+fls[i].code+"'>"+fls[i].name+"</option>";
        }*/
      //  $("#cucustomerstype1").append(options);



    }
});

//setselecttype(salesmanCodes,"share");
/*setselecttype(salemans,"share");*/
/*if(!isGLY()){
    $("#salesmandiv").css("display","none");
}*/
//setType();
form.render();

function setselecttype(dt,key) {
 var options="";
 for(var i=0;i<dt.length;i++){
     options+="<option value='"+dt[i].code+"'>"+dt[i].name+"</option>";
 }
 $("#"+key+"").append(options);

}
function getselectText( dt,key){
    $("[data-field = '"+key+"']").children().each(function(){
        for(var i=0;i<dt.length;i++){
            if($(this).text() == dt[i].code){
                $(this).text(dt[i].name);
            }
        }
    })
}
//查询条件
table.on('toolbar(customertable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    var data = checkStatus.data;
    var cucustomers = $('#cucustomers').val();//客户名称
    var cucustomerstype = $("input[name='cucustomerstype1']")[0].value;//$('#cucustomerstype1 option:selected').val();//客户类型
    if(cucustomerstype==""){
        for(var i=0;i<fls.length;i++){
            cucustomerstype=cucustomerstype+","+fls[i].code;
        }
    }
    if(cucustomerstype==""){
       for(var i=0;i<fls.length;i++){
           cucustomerstype=cucustomerstype+","+fls[i].code;
       }
    }
    if(salesmanCodes.options != undefined){
        salesmanCodes=user.code;
    }
    var saleman=salesmanCodes;//$('#salesman option:selected').val();//所属业务员
    if(saleman==undefined)saleman="";
    switch(obj.event){
        case 'shared':
            if(data.length ==0){
                layer.msg("请选择要共享的客户");
                break;
            }
          /*  for(var i=0;i<data.length;i++){
                if(data[i].processid ==null){
                    layer.msg("选择的数据未审批，不能进行共享");
                    return;
                }
            }*/

            for (var i = 0;i<data.length;i++){
                sharecustomer.push(data[i].code)
            }
            //initable33();
            layer.open({
                type: 1,
                title: "共享客户",
                area: ['300px', '200px'],
                content: $("#shared"),//引用的弹出层的页面层的方式加载修改界面表单
                success: function(layero, index){
                    ////console.log(layero, index);
                    initable33();
                }
            });
            break;
        case 'new'://新增
            parent.intab("views/jsp/BasicData/tpl/customerinfo.jsp","添加客户信息")
            break;
        case 'delet'://删除
            var delid = [];
            for (var i = 0;i<data.length;i++){
                if(data[i].processid !=null){
                    layer.msg("选择的数据已发起审批，不能进行删除");
                    return;
                }
                delid.push(data[i].id)
            }
            if(delid.length==0){
                layer.msg("请选择要删除的数据");
                break;
            }
            if(delCustomer(delid)){
                layer.msg("删除成功");
                table.reload('customertableid', {
                    type: 'get'
                    , url: 'customer/selectByPage'
                    ,   page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where:{
                        "type":cucustomerstype,
                        "type2":type2,
                        "name":cucustomers,
                        "saleman":saleman
                    }

                }, 'data');
            }else{
                layer.msg("删除失败");
            }
           // layer.msg('需要删除的数据ID为：'+ JSON.stringify(delid) + ',执行删除');

            break;
        case 'searchs':
           // var salesman = $('#salesman option:selected').val();//所属业务员
           // layer.msg("搜索"+cucustomers+","+cucustomerstype+","+salesman);
            //执行重载
            table.reload('customertableid', {
                type: 'get'
               , url: 'customer/selectByPage'
               ,page: {
                    curr: 1 //重新从第 1 页开始
                }
                ,where:{
                    "type":cucustomerstype,
                    "type2":type2,
                    "name":cucustomers,
                    "saleman":saleman
                }

            }, 'data');
            //下拉列表重新赋值
            //setselecttype(fls,"cucustomerstype1");
           // setselecttype(salemans,"salesman");
            setselecttype(salemans,"share");
            getxmselect2("#cucustomerstype2","cucustomerstype1", getxmlselectfls(fls));
            break;
        case 'publicpool':
            if(data.length==0){
                layer.msg('请选择加入公共池的客户')
            }else{
                var delid = [];
                for (var i = 0;i<data.length;i++){
                    if(data[i].processid ==null){
                        layer.msg("选择的数据未审批，不能加入公共池");
                        return;
                    }
                    delid.push(data[i].id)
                }
                if(addpublicPool(delid)){
                    layer.msg("加入公共池成功");

                    //执行重载
                    table.reload('customertableid', {
                        type: 'get'
                        , url: 'customer/selectByPage'
                        ,page: {
                            curr: 1 //重新从第 1 页开始
                        }
                        ,where:{
                            "type":cucustomerstype,
                            "type2":type2,
                            "name":cucustomers,
                            "saleman":saleman
                        }

                    }, 'data');

                }else{
                    layer.msg("加入公共池失败");
                }
               // layer.msg('需要加入公共池的数据ID为：'+ JSON.stringify(delid));
            }
            break;

    };
    form.render();
});
//审批时使用的
let approveData;
//修改、查看
table.on('tool(customertable)', function(obj){
    var data = obj.data;
    if(obj.event === 'customerup') {
        parent.intab("views/jsp/BasicData/tpl/customerinfo.jsp?id="+obj.data.id,"修改客户信息")
        window.sessionStorage.setItem("processid",data.processid);

        window.sessionStorage.setItem("customerinfoSpstatus",data.spstatus);
    }else if(obj.event === 'customerstname' || obj.event === 'cucustomerscode' || obj.event === 'referred') {
        parent.intab("views/jsp/BasicData/tpl/viewcustomerinfo.jsp?id="+obj.data.id,"客户信息")
    }else if(obj.event === 'addB'){

        var param={};
        param.status="B";
        param.id=obj.data.id;
        if(update(param)){
            layer.msg("添加黑名单成功!");
            refash();
        }else{
            layer.msg("添加黑名单失败!");
        }
        //调用更新方法更新状态
    }else if(obj.event === 'cacleB'){
        //调用更新方法更新状态
        var param={};
        param.status="";
        param.id=obj.data.id;
        if(update(param)){
            layer.msg("取消黑名单成功!");
            refash();
        }else{
            layer.msg("取消黑名单失败!");
        }
    }else if(obj.event === 'submits'){
        //调用更新方法更新状态
        var param={};
        param.spstatus=2;
        param.id=obj.data.id;
        if(updateSpStatus(param)){
            layer.msg("提交审批成功!");
            refash();
        }else{
            layer.msg("提交审批失败!");
        }

    }else if(obj.event === 'through'){
        approveData=obj.data
        //审批通过之前弹出询问框
        shareopenwind= layer.open({
            type: 1,
            title: "设置",
            area: ['500px', '600px'],
            content: $("#setCustomerType")//引用的弹出层的页面层的方式加载修改界面表单
        });

    }else if(obj.event === 'backtothe'){
        //调用更新方法更新状态
        var param={};
        param.spstatus=1;
        param.id=obj.data.id;
        if(updateSpStatus(param)){
            layer.msg("审批退回成功!");
            refash();
        }else{
            layer.msg("审批退回失败!");
        }
    }
});
//监听提交,审批通过
form.on('submit(setCustomerTypeSubmit)', function(data){
    //调用更新方法更新状态
    var param1={};
    param1.spstatus=3;
    param1.id=approveData.id;

    var param2={};
    param2.id=approveData.id;
    param2.type=data.field.customerType;

    let flag=updateSpStatus(param1) && updateCustomerType(param2) ;

    if(flag){
        layer.msg("审批通过成功!");
        refash();
    }else{
        layer.msg("审批通过失败!");
    }

});

//判断当前登录用户是否为 营销部门的总监 角色
function is_marketing_director() {
    $.ajax({
        url:'customer/isMarketingDirector',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                isMarketingDirector=da.data;
            }
        }
    });
}
function refash() {
    var cucustomers = $('#cucustomers').val();//客户名称
    var cucustomerstype = $("input[name='cucustomerstype1']")[0].value;//$('#cucustomerstype1 option:selected').val();//客户类型
    if(cucustomerstype==""){
        for(var i=0;i<fls.length;i++){
            cucustomerstype=cucustomerstype+","+fls[i].code;
        }
    }
    if(cucustomerstype==""){
        for(var i=0;i<fls.length;i++){
            cucustomerstype=cucustomerstype+","+fls[i].code;
        }
    }
    if(salesmanCodes.options != undefined){
        salesmanCodes=user.code;
    }
    var saleman=salesmanCodes;//$('#salesman option:selected').val();//所属业务员
    if(saleman==undefined)saleman="";
    //执行重载
    table.reload('customertableid', {
        type: 'get'
        , url: 'customer/selectByPage'
        ,page: {
            curr: 1, //重新从第 1 页开始
            limit:50
        }
        ,where:{
            "type":cucustomerstype,
            "type2":type2,
            "name":cucustomers,
            "saleman":saleman
        }

    }, 'data');

    setselecttype(salemans,"share");
    getxmselect2("#cucustomerstype2","cucustomerstype1", getxmlselectfls(fls));
}

function update(data){
    var tf=false;
    $.ajax({
        type : 'get',
        //  url : 'resource/getTree',
        data:{"id":data.id,"status":data.status},
        url:'customer/updateHByKey',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}
//更改审批状态
function updateSpStatus(data){
    var tf=false;
    $.ajax({
        type : 'get',
        data:{"id":data.id,"spstatus":data.spstatus},
        url:'customer/updateSpStatus',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        }
    });
    return tf;
}
//更改客户类型
function updateCustomerType(data){
    var tf=false;
    $.ajax({
        type : 'get',
        data:{"id":data.id,"type":data.type},
        url:'customer/updateCustomerType',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        }
    });
    return tf;
}

//更新授信
function updateCredit(data){
    var tf=false;
    $.ajax({
        type : 'get',
        data:{"ids":JSON.stringify(data.ids),"isCredit":data.isCredit},
        url:'customer/updateCredit',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        }
    });
    return tf;
}
//---联系人查询
table.render({
    elem: '#contactselect'
    ,type:"get"
    ,url:"customercontact/select2ByPage"
    ,where:{
        "company":"",
        "name":"",
        "email":""
    }
    ,toolbar: '#contactquerytoolbar'
    ,cols: [[
        {checkbox: true, fixed: true}
        ,{field:'companyname', title:'公司名称', sort: true, event: "companyaffiliation"}
        ,{field:'name', title:'联系人名称', sort: true, event: "contactname"}
        ,{field:'email', title:'邮箱地址', sort: true}
        ,{field:'post', title:'职务', sort: true}
        ,{field:'tel', title:'电话', sort: true}
        ,{field:'phone', title:'手机', sort: true}
        ,{field:'wx', title:'微信', sort: true}
        ,{field:'expressAddress', title:'快件地址', sort: true}
        ,{field:'birthday', title:'联系人生日', sort: true}
        ,{field:'remark', title:'联系人备注', sort: true}
        // ,{field:'salesman', title:'业务员', sort: true}
        //,{fixed: 'right', width:150, align:'center', toolbar: '#customerup', title:'操作'}
    ]]
    ,id: 'contacttableid'
    ,height: $(document).height() - $('#contactselect').offset().top - 50
    ,page: true

});
//联系人，双击
table.on('tool(contacttable)', function(obj){
    var data = obj.data;
    //根据供应商编码获取供应商id
    var id= getIdBycode(data.company);
    data.id=id;
    if(obj.event === 'companyaffiliation' || obj.event === 'contactname') {
        parent.intab("views/jsp/BasicData/tpl/viewcustomerinfo.jsp?id="+data.id,"客户信息")
    }

});
//联系人查询条件
table.on('toolbar(contacttable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'searchs':
            var contactinfo = $('#contactinfo').val();
            var contactemail = $('#contactemail').val();
           // layer.msg("搜索"+contactinfo+","+contactemail);
            //执行重载
            table.reload('contacttableid', {
                type:"get"
                ,url:"customercontact/select2ByPage"
                ,where:{
                "company":"",
                "name":contactinfo,
                "email":contactemail
               },
                page: {
                    curr: 1 //重新从第 1 页开始
                }

            }, 'data');
            $('#contactinfo').val(contactinfo);
            $('#contactemail').val(contactemail);
            break;
        case 'clear':
            $('#contactinfo').val("");
            $('#contactemail').val("");
            break;
    }
});

//---公共客户池
table.render({
    elem: '#customerpoolselect'
    , type: 'get'
    , url: 'customer/select3ByPage'
    ,where:{
        "name":"",
        "type":type
    }
    , toolbar: '#commonclienttoolbar'
    , cols: [[
        {checkbox: true, fixed: true}
        , {field: 'type', title: '客户类型', fixed: true}
        , {field: 'name', title: '客户名称', fixed: true, event: "customerstname"}
        , {field: 'code', title: '客户代码', fixed: true, event: "cucustomerscode"}
        , {field: 'abbreviation', title: '简称', fixed: true, event: "referred"}
        , {field: 'emailStr', title: '邮件', fixed: true, event: "referred"}
        , {field: 'country', title: '国家', fixed: true}
        , {field: 'level', title: '客户等级', fixed: true}
        , {field: 'sourceOfCustomers', title: '客户来源', fixed: true}
        , {field: 'businessType', title: '业务类型', fixed: true}
        , {field: 'shortCode', title: '客户三位简码',width: 200 }
        // , {field: 'creater', title: '创建者', fixed: true}

    ]]
    ,id: 'customerpooltableid'
    ,height:  $(document).height() - $('#customerpoolselect').offset().top - 50
    ,page: true
    , limit: 50
    , limits: [50,100,200,300, 500]
    , done: function (res, curr, count) {
        //客户类型
        getselectText(fls,"type");
        //国家
        getselectText(countrys,"country");
        //客户等级
        getselectText(djs,"level");
        //客户来源
        getselectText(sourceOfCustomerss,"sourceOfCustomers");
        //业务类型
        getselectText(businessTypes,"businessType");
        //审批状态
        getselectText(spstatuss,"spstatus");

       // setselecttype(fls,"cocustomerstype2");

    }
});
table.on('tool(customerpooltable)', function(obj){
    var data = obj.data;
    if(obj.event === 'customerstname' || obj.event === 'cucustomerscode' || obj.event === 'referred') {
        parent.intab("views/jsp/BasicData/tpl/viewcustomerinfo.jsp?id="+obj.data.id,"客户信息")
    }
});
//公共池
table.on('toolbar(customerpooltable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    var data = checkStatus.data;
    var cocustomersinfo = $('#cocustomersinfo').val();
    var cocustomerstype =$("input[name='cucustomerstype22']")[0].value;
    if(cocustomerstype==""){
        for(var i=0;i<fls.length;i++){
            cocustomerstype=cocustomerstype+","+fls[i].code;
        }
    }
   // var days=$("input[name='days']")[0].value;
    switch(obj.event){
        case 'dicustomers':
            if(data.length==0){
                layer.msg('请选择需要分配客户')
            }else{
                var delid = [];
                for (var i = 0;i<data.length;i++){
                    delid.push(data[i].id)
                }
                distributionid = delid;
                layer.open({
                    type: 1,
                    title: "分配客户",
                    area: ['300px', '200px'],
                    content: $("#dicustomers")//引用的弹出层的页面层的方式加载修改界面表单
                });

                //ajax得到业务员列表 给select赋值
                $("#customersalesman").html("");
                var customerdata = getusers();//[{name:"text1",value:"text1"},{name:"text2",value:"text2"}];

                for(var i =0;i<customerdata.length;i++){
                    $("#customersalesman").append("<option value=\""+customerdata[i].code+"\">"+customerdata[i].name+"</option>");
                }
                form.render('select');

                //layer.msg('需要设为自己的客户的数据ID为：'+ JSON.stringify(distributionid));
            }
            break
        case 'searchs'://搜索

           // layer.msg("搜索"+cocustomersinfo+","+cocustomerstype);
            //执行重载
            table.reload('customerpooltableid', {
                type: 'get'
                , url: 'customer/select3ByPage'
                ,where:{
                    "name":cocustomersinfo,
                    "type":cocustomerstype
                },
                page: {
                    limit: 50,
                    curr: 1 //重新从第 1 页开始
                }

            }, 'data');
            //类型

            getxmselect2("#cucustomerstype22","cucustomerstype22", getxmlselectfls(fls));
            initable22();
            form.render();
            break;
        case 'setcustomer'://设为自己
            if(data.length==0){
                layer.msg('请选择设为自己的客户')
            }else{
                var delid = [];
                for (var i = 0;i<data.length;i++){
                    delid.push(data[i].id)
                }
                if(setself(delid)){
                    layer.msg("设置成功");
                    //执行重载
                    table.reload('customerpooltableid', {
                        type: 'get'
                        , url: 'customer/select3ByPage'
                        ,where:{
                            "name":cocustomersinfo,
                            "type":cocustomerstype
                        },
                        page: {
                            limit: 50,
                            curr: 1 //重新从第 1 页开始
                        }

                    }, 'data');
                }else{
                    layer.msg("设置失败");
                }
               // layer.msg('需要设为自己的客户的数据ID为：'+ JSON.stringify(delid));
            }
            break;
        // case 'insertpublic':
        //     pubPool();
        //     //autoincreatepool
        //     layer.open({
        //         type: 1,
        //         title: "自动加入公共池配置",
        //         area: ['600px', '100%'],
        //         content: $("#autoincreatepool")//引用的弹出层的页面层的方式加载修改界面表单
        //     });
        //
        //
        //     //insertAutoPoolSet(cocustomerstype,days);
        //    //getxmselect2("#cucustomerstype22","cucustomerstype22", getxmlselectfls(fls));
        //
        //     initable22();
        //     form.render();
        //     break;
        // case 'potentialCustomerNotExport':
        //     customerNotExport();
        //     form.render();
        //     break;
        // case 'potentialCustomerLastExport':
        //     customerLastExport();
        //     form.render();
        //     break;
    };

   // getxmselect2("#cucustomerstype2","cucustomerstype1", getxmlselectfls(fls));
    getxmselect2("#cucustomerstype22","cucustomerstype22", getxmlselectfls(fls));
});



form.render();
//监听提交,转移
form.on('submit(transferSubmit)', function(data){
    if(data.field.salesmanCode == ""){
        layer.msg("请选择业务员！", {icon: 6});
        return  false;
    }
    if(transferFun(data.field.salesmanCode)){
        layer.msg("转移成功" );
        setTimeout(function(){
            layer.closeAll();
        },2000);
        //执行重载
        table.reload('customertableid', {
            type: 'get'
            , url: 'customer/selectByPage'
            ,page: {
                curr: 1 //重新从第 1 页开始
            }
            ,where:{
                "type":cucustomerstype,
                "type2":type2,
                "name":cucustomers,
                "saleman":saleman
            }

        }, 'data');

    }else {
        layer.msg("转移失败" );
    }
    return false;
});
//监听提交,共享客户
form.on('submit(sharesubmit)', function(data){
   // var cocustomersinfo = $('#cocustomersinfo').val();
   // var usercode = $('#share option:selected').val();
   /* if(data.field.share == ""){
        layer.msg("请选择业务员！", {icon: 6});
        return  false;
    }*/
    if(saveshare(data.field.share)){
        layer.msg("共享客户成功" );
        setTimeout(function(){
           // initable33();
            layer.closeAll(function(){ //关闭所有层并执行回调
                share22.setValue([]);
            });
        },2000);
    }else {
        layer.msg("共享客户失败" );
    }

   // layer.closeAll();
   // share22.options.data=[];
    return false;
});
//监听提交,分配客户
form.on('submit(dicustomerssubmit)', function(data){
    var cocustomersinfo = $('#cocustomersinfo').val();
    var cocustomerstype = $('#cocustomerstype option:selected').val();
    if(savefp(data)){
        layer.msg("分配客户成功", {icon: 6});
        //执行重载
        table.reload('customerpooltableid', {
            type: 'get'
            , url: 'customer/select3ByPage'
            ,where:{
                "name":cocustomersinfo,
                "type":cocustomerstype
            },
            page: {
                limit: 50,
                curr: 1 //重新从第 1 页开始
            }

        }, 'data');
    }else {
        layer.msg("分配客户失败", {icon: 6});
    }
     layer.closeAll();
    //layer.close(shareopenwind);
    //data.field 为表单数据 distributionid为需要分配的客户ID

    return false;
});
/*$("#customerstatistics").on("click",function () {
    parent.intab("views/jsp/WarehouseManagement/tpl/statistics.jsp","客户统计");
})
$("#commonsettings").on("click",function () {
    parent.intab("views/jsp/BasicData/tpl/commonsettings.jsp","公共池设置");
})*/

layui.use(['dropdown'], function () {
    let dropdown = layui.dropdown;
    dropdown.onFilter("customerstatistics", function (event) {
        switch (event) {
            case "s1":
                parent.intab("views/jsp/report/reportCustomerRL.jsp?ym=customerRL","业务员从公共池认领客户")
                break
            case "s2":
                parent.intab("views/jsp/report/reportCustomerShare.jsp?ym=customerShare","客户转入公共池详情表")
                break
            case "s3":
                parent.intab("views/jsp/report/reportCount.jsp?ym=customerCount","客户帐期详情")
                break
            case "s4":
                parent.intab("views/jsp/report/customerInformationRecord.jsp","客户信息记录")
                break
            case "S5":
                parent.intab("views/jsp/report/customerBillingPeriod.jsp","新客户账期详情")
                break
            case "S6":
                parent.intab("views/jsp/report/customerOrderAndShipInfo.jsp","客户下单出货记录")
                break
        }
    });
    dropdown.onFilter("commonsettings", function (event) {
        switch (event) {
            case "s1":
                //autoincreatepool
                pubPool(1);
                editTable('s1');
                layer.open({
                    type: 1,
                    title: "N天邮件未联系,自动加入公共池(潜在客户)",
                    area: ['600px'],
                    content: $("#autoincreatepool")//引用的弹出层的页面层的方式加载修改界面表单
                });
                initable22();
                form.render();
                break
            case "s2":
                // customerNotExport();
                pubPool(2);
                editTable('s2');
                layer.open({
                    type: 1,
                    title: "初次邮件联系后，N天未成单，自动加入公共池 （潜在客户）",
                    area: ['600px'],
                    content: $("#autoincreatepool")
                });

                initable22();
                form.render();
                break
            case "s3":
                // customerLastExport();
                pubPool(3);
                editTable('s3');
                layer.open({
                    type: 1,
                    title: "距最近成单后，N天未成单，自动加入公共池（合作客户）",
                    area: ['600px'],
                    content: $("#autoincreatepool")
                });
                initable22();
                form.render();
                break
        }
    });
})

//批量删除
function delCustomer(ids) {
    var tf=false;
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:{"ids":JSON.stringify(ids)},
        url:'customer/delete',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}

//加入公共池
function addpublicPool(ids) {
    var tf=false;
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:{"ids":JSON.stringify(ids)},
        url:'customer/update',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}
//设为自己
function  setself(ids) {
    var tf=false;
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:{"ids":JSON.stringify(ids)},
        url:'customer/setself',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}
function getusers() {
    var tf=[];
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        //data:{"ids":JSON.stringify(ids)},
        url:'customer/getusers',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}
//分配客户
function  savefp(data) {
    /*distributionid[0]//
    data.field.customersalesman;*/
    var tf=false;
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:{"ids":JSON.stringify(distributionid),"saleman":data.field.customersalesman},
        url:'customer/savefp',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;

}
function  querysalemans() {
var sms=[];
 var objs= getusers();
 for(var i=0;i<objs.length;i++){
     var obj={};
     obj.code=objs[i].code;
     obj.name=objs[i].name;
     sms.push(obj);
 }
 return sms;
}
//判断是否是管理员
function  isGLY() {
    var tf=false;
    $.ajax({
        type : 'get',
        //  url : 'resource/getTree',
        //data:{"ids":JSON.stringify(ids)},
        url:'customer/isGLY',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}
function  getIdBycode(code) {
    var tf=0;
    $.ajax({
        type : 'get',
        //  url : 'resource/getTree',
        data:{"code":JSON.stringify(code)},
        url:'customer/getIdBycode',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}
function transferFun(salCode) {
    var tf=false;
    $.ajax({
        type : 'POST',
        data:{"salesmanCode":salCode,"codes":JSON.stringify(sharecustomer)},
        url:'customer/saveTransfer',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        }
    });
    return tf;
}

function  saveshare(usercode) {
   let datas= table.checkStatus("customertableid").data
    sharecustomer=[];
    for(var i=0;i<datas.length;i++){
        sharecustomer.push(datas[i].code);
    }
    var tf=false;
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:{"usercode":JSON.stringify(usercode),"codes":JSON.stringify(sharecustomer)},
        url:'customer/saveshare',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}


function getxmlselectfls(){
    tmparr=[]
    for(let item of fls){
        tmparr.push({value:item.code,name:item.name})
    }
    return tmparr
}
/* getxmselect2("#cucustomerstype2","cucustomerstype1", getxmlselectfls(fls));
getxmselect2("#cucustomerstype22","cucustomerstype22", getxmlselectfls(fls));*/
function getxmselect2(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
           /* //return this
            salesmanCodes="";
            for(var i=0;i<change.length;i++){
                if(i == change.length-1){
                    salesmanCodes=salesmanCodes+ change[i].value;
                }else{
                    salesmanCodes=salesmanCodes+ change[i].value+",";
                }
            }*/

        }
    })
}

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                    item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getAllJson2(jsons,moren) {//moren:默认选择
     var arrays=moren.split(",");
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];

        let onoff=arrays.findIndex(d=>d==item["code"])+1
        tmparr["checked"]=onoff?true:false
        /*for(var i=0;i<arrays.length;i++ ){
            if(tmparr["value"]==arrays[i]){
                tmparr["selected"]=true;
                break;
            }
        }*/
        if(item["users"]){
            for(let it of item["users"]){


                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"],moren);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}
function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            //return this
            salesmanCodes="";
            for(var i=0;i<change.length;i++){
                if(i == change.length-1){
                    salesmanCodes=salesmanCodes+ change[i].value;
                }else{
                    salesmanCodes=salesmanCodes+ change[i].value+",";
                }
            }

        }
    })
}
function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            //return this
            salesmanCodes="";
            for(var i=0;i<change.length;i++){
                if(i == change.length-1){
                    salesmanCodes=salesmanCodes+ change[i].value;
                }else{
                    salesmanCodes=salesmanCodes+ change[i].value+",";
                }
            }

        }
    })
}

function getxmselect222(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            //return this
          /*  share22="";
            for(var i=0;i<change.length;i++){
                if(i == change.length-1){
                    share22=share22+ change[i].value;
                }else{
                    share22=share22+ change[i].value+",";
                }
            }*/

        }
    })
}
//单选下拉框
function getXmSelectRadio(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        radio: true,
        clickClose: true,
        height: 'auto',
        data: data,
    })
}

function codeConvertValue(arrays){
    let tmparr=[]
    for(let item of arrays){
        tmparr.push({value:item.code,name:item.name})
    }
    return tmparr
}

function initable22() {
//select over

//获取当前用户的部门及人员结构树
    let treeList = userTree;//getCurrentDepartmentUser2();ssssss

    if(treeList && treeList.list){
        let userTree = getAllJson(treeList.list);
        salesmanCodes= getxmselect("#salesman","subordinatesalesman", userTree);
    }else {
        //  getxmselect("#operationCode","owneroperator", [{name: user.name, value: user.code}]);
        salesmanCodes= getxmselect("#salesman","subordinatesalesman", [{name: user.name, value: user.code}]);
    }

    //客户来源
    let sourceOfCustomerTree=codeConvertValue(sourceOfCustomerss);
    sourceOfCustomerList=getxmselect("#sourceOfCustomers","sourceOfCustomers", sourceOfCustomerTree);

    //客户来源
    let attributesOfCustomerTree=codeConvertValue(attributesOfCustomers);
    attributesOfCustomerList=getxmselect("#attributesOfCustomers","attributesOfCustomers", attributesOfCustomerTree);

    let isMakerTree=[
        {name: '是', value: 1},
        {name: '否', value: 2},
    ];
    isMakerList=getXmSelectRadio("#isMaker","isMaker", isMakerTree)
}
// 请求等待
function showLoad() {
    return layer.load(2, {
        shade: [0.4, '#000'],
        content: '加载中...',
        success: function (layero) {
            layero.find('.layui-layer-content').css({
                'padding-top': '40px',
                'width': '200px'
            });
        }
    });
}

/**
 * 保存自动进入公共池的配置
 * @param type
 * @param days
 */
function  insertAutoPoolSet(type,days,poolType) {
    let index=showLoad();
    $.ajax({
        type : 'get',
        data:{"type":type,days:days,"poolType":poolType},
        url:'customer/insertAutoPoolSet',
        dataType:"json",
        success : function (da) {
            if(da.status==200 ){
             layer.msg("保存成功！");
            }else {
                layer.msg("保存失败！");
            }
            layer.close(index);
            return false;
        }
    });

}
//未成单客户自动加入公共池
function customerNotExport(type,days,poolType){
    let index=showLoad();
    $.ajax({
        type : 'get',
        data:{"type":type,days:days,poolType:poolType},
        url:'customer/potentialCustomerNotExport',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                layer.msg("保存成功！");
            }else {
                layer.msg("保存失败！");
            }
            layer.close(index);
            return false;
        }
    });
}
//距上次成单客户加入公共池
function customerLastExport(type,days,poolType){
    let index=showLoad();
    $.ajax({
        type : 'get',
        data:{"type":type,"days":days,poolType:poolType},
        url:'customer/potentialCustomerLastExport',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                layer.msg("保存成功！");
            }else {
                layer.msg("保存失败！");
            }
            layer.close(index);
            return false;
        }
    });

}


var poolData=[];
function pubPool(poolType) {
    poolData=[];

    if (poolType==1 || poolType==2){//潜在
        for(var i=0;i<fls.length;i++){
            if (fls[i].name.indexOf("合作")!=0){
                poolData.push({"code":fls[i].code,"name":fls[i].name,"days":""});
            }
        }
    }else {//合作
        for(var i=0;i<fls.length;i++){
            if (fls[i].name.indexOf("合作")==0){
                poolData.push({"code":fls[i].code,"name":fls[i].name,"days":""});
            }
        }
    }

    //取配置数据
    var pool=getPoolData(poolType);
 for(var i=0;i<pool.length;i++){
     for(var n=0;n<poolData.length;n++){
         if(poolData[n].code==pool[i].type){
             poolData[n].days=pool[i].days;
             break;
         }
     }
 }
//自动加入公共池
    table.render({
        elem: '#autoincreatepooltable'
        , data: poolData
        , cols: [[
            {field: 'code', title: '客户类型编码', hide: true}
            , {field: 'name', title: '客户类型',width:400}
            , {field: 'days', title: '天数(点击可编辑)',width:180, align: 'center', edit:"text"}

        ]]
        , id: 'autoincreatepooltableid'
        , height: 400// $(document).height() - $('#autoincreatepooltable').offset().top - 50
        ,skin: 'line'
        ,even:true
        , page: false
        , done: function (res, curr, count) {


        }
    });
}
function editTable(value){
    switch (value) {
        case 's1':
            //监听单元格编辑
            table.on('edit(autoincreatepooltable)', function(obj){
                var data = obj.data; //得到修改后的值
                insertAutoPoolSet(data.code,data.days,1);
            });
            break;
        case 's2':
            //监听单元格编辑
            table.on('edit(autoincreatepooltable)', function(obj){
                var data = obj.data; //得到修改后的值
                customerNotExport(data.code,data.days,2);
            });
            break;
        case 's3':
            //监听单元格编辑
            table.on('edit(autoincreatepooltable)', function(obj){
                var data = obj.data; //得到修改后的值
                customerLastExport(data.code,data.days,3);
            });
            break;
    }

}


function getPoolData(poolType){
  var obj=[];
    $.ajax({
        type : 'get',
        data:{"poolType":poolType},
        url:'customer/getPoolData',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                obj=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return obj;
}

$("#autoincreatepoolsubmit").on("click",function(){

  //  savepool()
    layer.closeAll();
});

//主页查询
$("#sharedZhu").on("click",function(){
    //共享
    var obj={};
    obj.event="shared";
    executeSearch(obj);
});
$("#new").on("click",function(){
    //新增
    var obj={};
    obj.event="new";
    executeSearch(obj);
});
$("#delet").on("click",function(){
    //删除
    var obj={};
    obj.event="delet";
    executeSearch(obj);
});
$("#print").on("click",function(){
    //删除
    var obj={};
    obj.event="print";
    executeSearch(obj);
});
$("#searchs").on("click",function(){
    // 搜索
    var obj={};
    obj.event="searchs";
    executeSearch(obj);
});
$("#addpubpool").on("click",function(){
    //加入公共池
    var obj={};
    obj.event="publicpool";
    executeSearch(obj);
});
$("#setUpCustomerCenter").on("click",function(){
    layer.open({
        title:'设置',
        type: 2,
        area: ['800px', '400px'],
        content: 'views/jsp/BasicData/tpl/setUpCustomerCenter.jsp'
    });
});
$("#updateSalesman").on("click",function(){
    //转移
    var obj={};
    obj.event="updateSalesman";
    executeSearch(obj);
});
$("#viewOffer").on("click",function(){
    //查看报价
    let obj={};
    obj.event="viewOffer";
    executeSearch(obj);
});
$("#viewContract").on("click",function(){
    //查看外销
    let obj={};
    obj.event="viewContract";
    executeSearch(obj);
});
$("#viewShipmentPlan").on("click",function(){
    //查看出运计划
    let obj={};
    obj.event="viewShipmentPlan";
    executeSearch(obj);
});
$("#viewBillExchange").on("click",function(){
    //查看出运计划
    let obj={};
    obj.event="viewBillExchange";
    executeSearch(obj);
});
$("#viewShipmentDetail").on("click",function(){
    //查看出运明细
    let obj={};
    obj.event="viewShipmentDetail";
    executeSearch(obj);
});
$("#viewEmail").on("click",function(){
    //邮件
    let obj={};
    obj.event="viewEmail";
    executeSearch(obj);
});
$("#uploadFile").on("click",function(){
    //文件上传
    let obj={};
    obj.event="uploadFile";
    executeSearch(obj);
});
$("#credit").on("click",function(){
    //文件上传
    let obj={};
    obj.event="credit";
    executeSearch(obj);
});
function  executeSearch(obj) {
    var checkStatus = table.checkStatus("customertableid");
    var data = checkStatus.data;
    var cucustomers = $('#cucustomers').val();//客户名称
    var cucustomerstype = $("input[name='cucustomerstype1']")[0].value;//$('#cucustomerstype1 option:selected').val();//客户类型
   /* if(cucustomerstype==""){
        for(var i=0;i<fls.length;i++){
            cucustomerstype=cucustomerstype+","+fls[i].code;
        }
    }*/
    if(cucustomerstype==""){
        for(var i=0;i<fls.length;i++){
            cucustomerstype=cucustomerstype+","+fls[i].code;
        }
    }
    if(salesmanCodes.options != undefined){
        salesmanCodes=user.customerRole;
    }
    var saleman=$("input[name='subordinatesalesman']")[0].value;//salesmanCodes;//$('#salesman option:selected').val();//所属业务员
    if(saleman==undefined)saleman="";

    let sourceOfCustomers=sourceOfCustomerList.getValue('valueStr')
    let attributesOfCustomers=attributesOfCustomerList.getValue('valueStr')
    let isMaker=isMakerList.getValue('valueStr')
    switch(obj.event){
        case 'shared':
            if(data.length ==0){
                layer.msg("请选择要共享的客户");
                break;
            }
            /*for(var i=0;i<data.length;i++){
                if(data[i].processid ==null){
                    layer.msg("选择的数据未审批，不能进行共享");
                    return;
                }
            }*/

            for (var i = 0;i<data.length;i++){
                sharecustomer.push(data[i].code)
            }

           shareopenwind= layer.open({
                type: 1,
                title: "共享客户",
                area: ['500px', '600px'],
                content: $("#shared")//引用的弹出层的页面层的方式加载修改界面表单
               ,end:function () {
                   share22.setValue([]);
               },
               success: function(layero, index){
                   ////console.log(layero, index);
                   let listitem=table.checkStatus("customertableid").data;
                   if(listitem.length>1){
                       share22.setValue([])
                   }else {
                       //let moren="RKB002";
                       let customerCode=table.checkStatus("customertableid").data[0].code;
                       let moren=getSharedByCustomerCode(customerCode);
                       share22.setValue(moren.split(","))
                   }

               }
            });
            break;
        case 'new'://新增
            parent.intab("views/jsp/BasicData/tpl/customerinfo.jsp","添加客户信息")
            break;
        case 'delet'://删除
            var delid = [];
            for (var i = 0;i<data.length;i++){
                if(data[i].processid !=null){
                    layer.msg("选择的数据已发起审批，不能进行删除");
                    return;
                }
                delid.push(data[i].id)
            }
            if(delid.length==0){
                layer.msg("请选择要删除的数据");
                break;
            }
            if(delCustomer(delid)){
                layer.msg("删除成功");
                table.reload('customertableid', {
                    type: 'get'
                    , url: 'customer/selectByPage'
                    ,   page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where:{
                        "type":cucustomerstype,
                        "type2":type2,
                        "name":cucustomers,
                        "saleman":saleman,
                        "sourceOfCustomers":sourceOfCustomers,
                        "attributesOfCustomers":attributesOfCustomers,
                        "isMaker":isMaker
                    }

                }, 'data');
            }else{
                layer.msg("删除失败");
            }
            // layer.msg('需要删除的数据ID为：'+ JSON.stringify(delid) + ',执行删除');

            break;
        case 'print':
            if(checkStatus.data.length > 1){
                layer.msg( "每次只能打印一个单据! ");
                break;
            }
            if(checkStatus.data.length == 0){
                layer.msg("请选择要打印的单据! ");
                break;
            }
            window.open("views/jsp/report.jsp?ym=customer&code=code:"+checkStatus.data[0].code);
            break;

        case 'searchs':
            // var salesman = $('#salesman option:selected').val();//所属业务员
            // layer.msg("搜索"+cucustomers+","+cucustomerstype+","+salesman);
            //执行重载
            table.reload('customertableid', {
                type: 'get'
                , url: 'customer/selectByPage'
                ,page: {
                    curr: 1 //重新从第 1 页开始
                }
                ,where:{
                    "type":cucustomerstype,
                    "type2":type2,
                    "name":cucustomers,
                    "saleman":saleman,
                    "sourceOfCustomers":sourceOfCustomers,
                    "attributesOfCustomers":attributesOfCustomers,
                    "isMaker":isMaker
                }

            }, 'data');
            break;
        case 'publicpool':
            if(data.length==0){
                layer.msg('请选择加入公共池的客户')
            }else{
                var delid = [];
                for (var i = 0;i<data.length;i++){
                    // if(data[i].processid ==null){
                    //     layer.msg("选择的数据未审批，不能加入公共池");
                    //     return;
                    // }
                    delid.push(data[i].id)
                }
                if(addpublicPool(delid)){
                    layer.msg("加入公共池成功");

                    //执行重载
                    table.reload('customertableid', {
                        type: 'get'
                        , url: 'customer/selectByPage'
                        ,page: {
                            curr: 1 //重新从第 1 页开始
                        }
                        ,where:{
                            "type":cucustomerstype,
                            "type2":type2,
                            "name":cucustomers,
                            "saleman":saleman
                        }

                    }, 'data');

                }else{
                    layer.msg("加入公共池失败");
                }
                // layer.msg('需要加入公共池的数据ID为：'+ JSON.stringify(delid));
            }
            break;
        case 'updateSalesman':
            if(data.length ==0){
                layer.msg("请选择客户");
                break;
            }
            for (var i = 0;i<data.length;i++){
                sharecustomer.push(data[i].code)
            }

            shareopenwind= layer.open({
                type: 1,
                title: "转移",
                area: ['500px', '300px'],
                content: $("#transferd")//引用的弹出层的页面层的方式加载修改界面表单
            });
            break;
        case 'uploadFile':
            parent.intab("views/jsp/BasicData/fileUpload.jsp?model=customer","文件上传")
            break;
        case 'viewOffer':
            if(data.length === 0){
                layer.msg("请选择一个客户");
                break;
            }
            if(data.length >= 2){
                layer.confirm('多个客户时默认查看第一个客户，确认继续？',confirmInfo(3,6), function (index) {
                    parent.intab("views/jsp/ExportBusiness/offer.jsp?customerName=" + encodeURI(data[0]["name"]),"报价")
                    layer.close(index);
                    return;
                })
                return;
            }
            parent.intab("views/jsp/ExportBusiness/offer.jsp?customerName=" + encodeURI(data[0]["name"]),"报价")
            break;
        case 'viewContract':
            if(data.length === 0){
                layer.msg("请选择一个客户");
                break;
            }
            if(data.length >= 2){
                layer.confirm('多个客户时默认查看第一个客户，确认继续？',confirmInfo(3,6), function (index) {
                    parent.intab("views/jsp/ExportBusiness/export.jsp?customerName=" + encodeURI(data[0]["name"]),"外销")
                    layer.close(index);
                    return;
                })
                return;
            }
            parent.intab("views/jsp/ExportBusiness/export.jsp?customerName=" + encodeURI(data[0]["name"]),"外销")
            break;
        case 'viewShipmentPlan':
            if(data.length === 0){
                layer.msg("请选择一个客户");
                break;
            }
            if(data.length >= 2){
                layer.confirm('多个客户时默认查看第一个客户，确认继续？',confirmInfo(3,6), function (index) {
                    parent.intab("views/jsp/ExportBusiness/shipmentplan.jsp?customerName=" + encodeURI(data[0]["name"]),"出运计划")
                    layer.close(index);
                    return;
                })
                return;
            }
            parent.intab("views/jsp/ExportBusiness/shipmentplan.jsp?customerName=" + encodeURI(data[0]["name"]),"出运计划")
            break;
        case 'viewBillExchange':
            if(data.length === 0){
                layer.msg("请选择一个客户");
                break;
            }
            if(data.length >= 2){
                layer.confirm('多个客户时默认查看第一个客户，确认继续？',confirmInfo(3,6), function (index) {
                    parent.intab("views/jsp/ExportBusiness/foreignexchangesettlement.jsp?customerName=" + encodeURI(data[0]["name"]),"结汇")
                    layer.close(index);
                    return;
                })
                return;
            }
            parent.intab("views/jsp/ExportBusiness/foreignexchangesettlement.jsp?customerName=" + encodeURI(data[0]["name"]),"结汇")
            break;
        case 'viewShipmentDetail':
            if(data.length === 0){
                layer.msg("请选择一个客户");
                break;
            }
            if(data.length >= 2){
                layer.confirm('多个客户时默认查看第一个客户，确认继续？',confirmInfo(3,6), function (index) {
                    parent.intab("views/jsp/ExportBusiness/shipmentdetails.jsp?customerName=" + encodeURI(data[0]["name"]),"出运明细")
                    layer.close(index);
                    return;
                })
                return;
            }
            parent.intab("views/jsp/ExportBusiness/shipmentdetails.jsp?customerName=" + encodeURI(data[0]["name"]),"出运明细")
            break;
        case 'viewEmail':
            if(data.length === 0){
                layer.msg("请选择一个客户");
                break;
            }
            if(data.length >= 2){
                layer.confirm('多个客户时默认查看第一个客户，确认继续？',confirmInfo(3,6), function (index) {
                    parent.intab("views/jsp/BasicData/email/index.jsp?id=4&custorID=" + data[0]["code"],"邮件")
                    layer.close(index);
                    return;
                })
                return;
            }
            parent.intab("views/jsp/BasicData/email/index.jsp?id=4&custorID=" + data[0]["code"],"邮件")
            break;
        case 'credit'://授信
            var delid = [];
            for (var i = 0;i<data.length;i++){
                if(data[i].spstatus !="3"){
                    layer.msg("选择的数据未审批，不能进行授信");
                    return;
                }
                delid.push(data[i].id)
            }
            if(delid.length==0){
                layer.msg("请选择要授信的数据");
                break;
            }
            let param={};
            param.ids=delid;
            param.isCredit=1
            if(updateCredit(param)){
                layer.msg("授信成功");
                table.reload('customertableid', {
                    type: 'get'
                    , url: 'customer/selectByPage'
                    ,   page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where:{
                        "type":cucustomerstype,
                        "type2":type2,
                        "name":cucustomers,
                        "saleman":saleman
                    }

                }, 'data');
            }else{
                layer.msg("授信失败");
            }
            break;

    };
    form.render();
}
//根据客户编码查询客户共享
function getSharedByCustomerCode(code) {
    let moren="";
    $.ajax({
        type : 'get',
        //  url : 'resource/getTree',
        data: {"code":code },
        url:'customer/getSharedByCustomerCode',
        dataType:"json",
        // contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
               moren=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return moren;
}
function initable33() {
   // share22.update({data:[]})
  //  share22= getxmselect222("#share","share", []);
    //查询当前选中的客户，只有一个客户时，查询接口取默认共享信息
  //
//获取当前用户的部门及人员结构树
    let treeList =userAllTree;// getCurrentDepartmentUser2(); 修改head。js中的方法取所有用户
    if(treeList && treeList.list){
        let userAllTree = getAllJson(treeList.list);
        return  getxmselect222("#share","share", userAllTree);
    }else {
       // let userAllTree = getAllJson(treeList.list);
        return getxmselect222("#share","share", [{name: user.name, value: user.code}]);
    }
    // share22.append(moren.split(","))

}
initable22();
share22=initable33();
getxmselect2("#cucustomerstype2","cucustomerstype1", getxmlselectfls(fls));
getxmselect2("#cucustomerstype22","cucustomerstype22", getxmlselectfls(fls));
//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}
/*
getLoginUserInfo();
function getLoginUserInfo() {
    let butDisplayOne = document.getElementById("butDisplayOne");
    let butDisplayTwo = document.getElementById("butDisplayTwo");
    if (user.code === "admin" ) {
        butDisplayTwo.style.display = "block";
    }else{
        butDisplayOne.style.display = "block";
    }
}*/
